import Vue from 'vue'
import Router from 'vue-router'
import store from '../store/index'
import goodStorage from 'good-storage'

import menus from '@/components/page/menu'
import WHeader from '@/components/header.vue'
import createMenu from '@/components/page/createMenu/createMenu'
import textReply from '@/components/page/textReply/textReply'
import login from '@/components/login/login'
import news from '@/components/page/news/news'

import user from '@/components/userPage/index'
import material from '@/components/materialPage/index'

Vue.use(Router)

const router = new Router({
  mode: 'history', // https://router.vuejs.org/zh-cn/api/options.html#mode
  history: true,
  routes: [
    {
      path: '/login',
      name: 'login',
      components: {
        content: login
      }
    },
    {
      path: '/',
      name: 'menu',
      components: {
        content: menus,
        header: WHeader
      },
      redirect: '/createMenu',
      children: [
        {
          path: '/createMenu',
          name: 'createMenu',
          component: createMenu,
          meta: {
            requireAuth: true // 添加该字段，表示进入这个路由是需要登录的
          }
        },
        {
          path: '/textReply',
          name: 'textReply',
          component: textReply,
          meta: {
            requireAuth: true // 添加该字段，表示进入这个路由是需要登录的
          }
        },
        {
          path: '/news',
          name: 'news',
          component: news,
          meta: {
            requireAuth: true // 添加该字段，表示进入这个路由是需要登录的
          }
        }
      ],
      meta: {
        requireAuth: true // 添加该字段，表示进入这个路由是需要登录的
      }
    },
    user,
    material
  ]
})
if (goodStorage.get('user')) {
  store.commit('SET_USER', goodStorage.get('user'))
}
router.beforeEach((to, from, next) => {
  if (to.meta.requireAuth) {
    if (store.state.modules.user.token !== '') { //  通过vuex state获取当前 的token是否存在
      next()
    } else {
      next({
        path: '/login',
        query: {redirect: to.fullPath} //  将跳转的路由path作为参数，登录成功后跳转到该路由
      })
    }
  } else {
    next()
  }
})

export default router
